#ifndef TIMERSERVER_H
#define TIMERSERVER_H

#include <QObject>
#include <QTcpSocket>
#include <QTcpServer>
#include <QMap>
#include <QTimer>

class TimerServer : public QObject
{
    Q_OBJECT
public:
    explicit TimerServer(QObject *parent = 0);

    /**
     * 广播给所有客户端消息
     * @brief Broadcast
     * @param name
     * @param cmd
     * @param time
     */
    void Broadcast(const QString &name,const QString &cmd,const QString &time);
    bool Start();
    void Stop();
    bool isStart();
    int clientNumber();

public:
    enum ClientType
    {
        CLI_NEW,
        CLI_MODIFY,
        CLI_REMOVE,
        ERR_MSG
    };
signals:
    /**
     * Client变化(增加/删除/变更名称等...)信号
     * @brief upClient
     * @param type ClientType
     * @param name
     * @param ip
     */
    void upClient(int type,const QString &name, const QString &ip);

public slots:
    void handle_newConnection();

    void handle_updateUserList();

    void handle_readyRead();

    void handle_error(QAbstractSocket::SocketError errors);
private:
    QTcpServer *m_tcpserver;
    QMap<QString, QTcpSocket *> m_userlist;

    //心跳
    QTimer *m_timer;

    //心跳时间
    int m_hearttime;

private:
    void initserver();
    void startHeart();
    void sendData(QTcpSocket *newtcpsocket, const QString &);
    void sendData(QTcpSocket *newtcpsocket, const QByteArray &data);
};

#endif // TIMERSERVER_H
